package com.sanjiahantang.ythshopping.activity.me;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.sanjiahantang.ythshopping.R;
import com.sanjiahantang.ythshopping.activity.BaseActivity;
import com.sanjiahantang.ythshopping.activity.GoodsInfoActivity;
import com.sanjiahantang.ythshopping.alipay.PayResult;
import com.sanjiahantang.ythshopping.config.ConfigValue;
import com.sanjiahantang.ythshopping.model.AliPatModel;
import com.sanjiahantang.ythshopping.model.BaseModel;
import com.sanjiahantang.ythshopping.model.OrderGoods;
import com.sanjiahantang.ythshopping.model.OrderInfor;
import com.sanjiahantang.ythshopping.model.OrderInforModel;
import com.sanjiahantang.ythshopping.model.WXpayModel;
import com.sanjiahantang.ythshopping.presenter.OrderInforPresenter;
import com.sanjiahantang.ythshopping.presenter.OrderManagerPresenter;
import com.sanjiahantang.ythshopping.presenter.PayActivePresenter;
import com.sanjiahantang.ythshopping.presenter.UseSurplusPresenter;
import com.sanjiahantang.ythshopping.utils.PayTypePopuwindow;
import com.sanjiahantang.ythshopping.utils.Utils;
import com.sanjiahantang.ythshopping.views.OrderInforView;
import com.sanjiahantang.ythshopping.views.OrderManagerView;
import com.sanjiahantang.ythshopping.views.PayActiveView;
import com.sanjiahantang.shopping.uilibrary.adapter.listview.BaseAdapterHelper;
import com.sanjiahantang.shopping.uilibrary.adapter.listview.QuickAdapter;
import com.sanjiahantang.shopping.uilibrary.uiutils.ListViewUtils;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.socialize.facebook.controller.utils.ToastUtil;

/**
 * Created by sks on 2015/9/30.
 * 查看订单信息
 */
public class LookOrderActivity extends BaseActivity implements View.OnClickListener,
        OrderInforView,OrderManagerView,AdapterView.OnItemClickListener, PayActiveView{
    TextView title;
    ImageView back;
    FrameLayout left;
    private Context context;
    private String orderID;
    private String logId;
    private OrderInforPresenter oiPresenter;
    private TextView txtOrderNum,txtName,txtPhone,txtAddress,txtPayMode,txtDistribution,
            txtTotal,txtFee,txtTime,txtActual,txtPay,txtCancel,txtBonus,txtIntegralMoney,txtBandMoney,
            txtBalance;
    private LinearLayout ll_integral;
    private TextView tv_integral;
    private EditText et_integral;
    private Button btn_integral;
    private RelativeLayout rlOrderBottom;
    private ListView listView;
    private QuickAdapter<OrderGoods> quickAdapter;
    private OrderInfor oiModel;
    private OrderManagerPresenter omPresenter;
    private UseSurplusPresenter userspresenter;
    private FrameLayout fl_main;
    private PayTypePopuwindow windoe;
    private ImageView ivIDCard;
    @Override
    public void initView() {
        super.initView();
        setContentView(R.layout.activity_lookorder);
        context = this;
        oiPresenter = new OrderInforPresenter(this);
        omPresenter = new OrderManagerPresenter(this);
        orderID = getIntent().getStringExtra("orderid");
        title=(TextView)findViewById(R.id.title);
        back = (ImageView)findViewById(R.id.back);
        left = (FrameLayout) findViewById(R.id.fl_Left);
        back.setBackgroundResource(R.mipmap.ic_back);
        title.setText("订单详情");
        left.setOnClickListener(this);
        ivIDCard = (ImageView) findViewById(R.id.ivIDCard);
        txtOrderNum = (TextView) findViewById(R.id.txtOrderNum);
        txtName = (TextView) findViewById(R.id.txtName);
        txtPhone = (TextView) findViewById(R.id.txtPhone);
        txtAddress = (TextView) findViewById(R.id.txtAddress);
        txtPayMode = (TextView) findViewById(R.id.txtPayMode);
        txtIntegralMoney = (TextView) findViewById(R.id.txtIntegralMoney);
        txtBandMoney = (TextView) findViewById(R.id.txtBandMoney);
        txtDistribution = (TextView) findViewById(R.id.txtDistribution);
        txtTotal = (TextView) findViewById(R.id.txtTotal);
        txtBalance = (TextView) findViewById(R.id.txt_balance_money);
        txtFee = (TextView) findViewById(R.id.txtFee);
        fl_main= (FrameLayout) findViewById(R.id.fl_lookorder_main);
        txtTime = (TextView) findViewById(R.id.txtTime);
        txtActual = (TextView) findViewById(R.id.txtActual);
        listView = (ListView) findViewById(R.id.listView);
        ll_integral= (LinearLayout) findViewById(R.id.ll_lookorder_integral);
        et_integral= (EditText) findViewById(R.id.et_lookorder_integral);
        tv_integral= (TextView) findViewById(R.id.tv_lookorder_integral);
        btn_integral= (Button) findViewById(R.id.btn_lookorder_integral);
        listView.setOnItemClickListener(this);
        ivIDCard.setOnClickListener(this);
        quickAdapter = new QuickAdapter<OrderGoods>(context,R.layout.order_good_item) {
            @Override
            protected void convert(BaseAdapterHelper helper, OrderGoods item) {
                Picasso.with(context).load(ConfigValue.IMG_IP
                        + item.getGoods_thumb())
                        .error(R.mipmap.ic_launcher)
                        .into((ImageView) helper.getView(R.id.imgGoods));
                helper.setText(R.id.txtTitle, item.getGoods_name());
                helper.setText(R.id.txtPrice, "￥" + item.getGoods_price());
                helper.setText(R.id.txtNumber,"数量：" + item.getGoods_number());
            }
        };
        rlOrderBottom = (RelativeLayout) findViewById(R.id.rlOrderBottom);
        listView.setAdapter(quickAdapter);
        txtPay = (TextView) findViewById(R.id.txtPay);
        txtCancel = (TextView) findViewById(R.id.txtCancel);
        txtPay.setOnClickListener(this);
        txtCancel.setOnClickListener(this);
        oiPresenter.loadOrderInfor(context,orderID);
        userspresenter=new UseSurplusPresenter(mContext,this);
    }
    private void showData(OrderInfor model){
        txtOrderNum.setText("订单号：" + model.getOrder_sn());
        txtName.setText(model.getConsignee());
        txtPhone.setText(model.getMobile());
        txtAddress.setText(model.getAddress());
        txtPayMode.setText(model.getPay_name());
        txtDistribution.setText(model.getShipping_name());
        if (model.getPay_set().equals("1") || Double.valueOf(model.getUser_surplus())<=0 || !model.getOrder_status().equals("1"))
        {
            ll_integral.setVisibility(View.GONE);
        }else {

            ll_integral.setVisibility(View.VISIBLE);
            tv_integral.setText("追加使用余额：(余额："+model.getUser_surplus()+")");

        }
        btn_integral.setOnClickListener(this);


        if (!model.getIntegral_money().equals("0.00") && !model.getIntegral_money().equals(""))
            txtIntegralMoney.setText("￥" + model.getIntegral_money());
        if (!model.getBond_money().equals("0.00") && !model.getBond_money().equals(""))
            txtBandMoney.setText("￥" + model.getBond_money());
        if (!model.getSurplus().equals("0.00") && !model.getSurplus().equals(""))
            txtBalance.setText("￥" + model.getSurplus());
        double priceTotal = 0;
        for (OrderGoods goods: model.getGoods()) {
            if(!TextUtils.isEmpty(goods.getGoods_price()) && !TextUtils.isEmpty(goods.getGoods_number())){
                priceTotal += Double.valueOf(goods.getGoods_price()) * Integer.valueOf(goods.getGoods_number());
            }else priceTotal = 0;

        }
        txtTotal.setText("￥" + priceTotal);
        txtFee.setText("+￥" + model.getShipping_fee());
        txtTime.setText(model.getAdd_time());
        txtActual.setText("实付款：￥" + model.getOrder_amount());
        quickAdapter.clear();
        quickAdapter.addAll(model.getGoods());

        if(model.getCard_img() == null){
            findViewById(R.id.rl_id_card).setVisibility(View.GONE);
        }else{
            findViewById(R.id.rl_id_card).setVisibility(View.VISIBLE);

            if(TextUtils.isEmpty(model.getCard_img())){
                findViewById(R.id.rl_id_card).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ToastUtil.showToast(context,"等待客服上传");
                    }
                });
            }else{
                Picasso.with(context).load(ConfigValue.IMG_IP + model.getCard_img()).into(ivIDCard, new Callback() {
                    @Override
                    public void onSuccess() {
                        ivIDCard.setTag(true);
                    }

                    @Override
                    public void onError() {
                        ivIDCard.setTag(false);
                    }
                });
                findViewById(R.id.rl_id_card).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (ivIDCard.getTag() != null && ((Boolean) ivIDCard.getTag()) == true){
                            ivIDCard.setVisibility(View.VISIBLE);
                        }else{
                            ToastUtil.showToast(context,"等待客服上传");
                        }

                    }
                });
            }

        }

        ListViewUtils.setListViewHeightBasedOnItems(listView);
        switch (Integer.parseInt(model.getOrder_status())){
            case 1:
                title.setText("待付款");
                break;
            case 2:
                title.setText("已取消");
                txtPay.setText("放回购物车");
//                txtCancel.setText("删除");
                txtCancel.setVisibility(View.GONE);
                break;
            case 3:
                title.setText("待发货");
                rlOrderBottom.setVisibility(View.GONE);
                break;
            case 4:
                title.setText("已发货");
                txtPay.setText("确认收货");
                txtCancel.setVisibility(View.GONE);
                break;
            case 5:
                title.setText("已完成");
                txtPay.setText("再次购买");
                txtCancel.setVisibility(View.GONE);
                break;
        }
    }
    //订单详情返回
    @Override
    public void result(OrderInforModel model) {
        if (model.getCode().equals("1")){
            oiModel = model.getData();
            logId = model.getData().getLog_id();
            showData(model.getData());
        }else
            Utils.showToast(context,model.getMsg());
    }

    @Override
    public void changeIntegral(BaseModel model) {
        if(model.getCode().equals("1")){
            oiPresenter.loadOrderInfor(context,orderID);
        }else {
            showToast(model.getMsg());
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.fl_Left:
                finish();
                break;
            case R.id.txtPay:
                switch (Integer.parseInt(oiModel.getOrder_status())){
                    case 1:
                        //支付
                        //pay();
                        if(windoe == null){
                            if("1".equals(oiModel.getPay_set()) && oiModel.getPayment_list().size() == 0){
                                ToastUtil.showToast(LookOrderActivity.this,"订单是海外支付订单,请访问PC端或者微信商城支付");
                                return;
                            }

                            windoe = new PayTypePopuwindow(LookOrderActivity.this, oiModel, new PayTypePopuwindow.AliCask() {
                                @Override
                                public void reAli(String ali) {

                                    aliinfo=ali;
                                    Thread payThread = new Thread(payRunnable);
                                    payThread.start();
                                }

                                @Override
                                public void reWX(WXpayModel wxpay) {
                                    getWXinfo(wxpay);
                                }
                            });
                        }

                        windoe.showAtLocation(fl_main, Gravity.BOTTOM,0,0);
                        break;
                    case 2:
                    case 5:
                        Utils.showDialog(LookOrderActivity.this, "提示", "是否重新放回购物车？", "", "", new View.OnClickListener() {

                            @Override
                            public void onClick(View view) {
                                switch (view.getId()) {
                                    case R.id.txtDialogCancel:
                                        Utils.dismissDialog();
                                        break;
                                    case R.id.txtDialogSure:
                                        omPresenter.cartOrder(context, orderID);
                                        Utils.dismissDialog();
                                        break;
                                }
                            }
                        });
                        break;
                    case 4:
                        Utils.showDialog(LookOrderActivity.this, "提示", "是否确认收货？", "", "", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                switch (view.getId()) {
                                    case R.id.txtDialogCancel:
                                        Utils.dismissDialog();
                                        break;
                                    case R.id.txtDialogSure:
                                        //确认收货
                                        omPresenter.sureOrder(context, orderID);
                                        Utils.dismissDialog();
                                        break;
                                }
                            }
                        });
                        break;
                }
                break;
            case R.id.txtCancel:
                switch (Integer.parseInt(oiModel.getOrder_status())){
                    case 1:
                        cancelOrder();
                        break;
                }
                break;
            case R.id.btn_lookorder_integral:
                final NumberSelectDialog pwddialog=new NumberSelectDialog(mContext);
                pwddialog.setOnPositiveListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        pwddialog.dismiss();
                        userspresenter.LoadSurolus(pwddialog.getnum(),et_integral.getText().toString(),orderID);

                    }
                });
                pwddialog.show();
                break;
            case R.id.ivIDCard:
                ivIDCard.setVisibility(View.GONE);
                break;
        }
    }
    private void cancelOrder(){
        Utils.showDialog(LookOrderActivity.this, "提示", "确认要取消订单吗？", "", "", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.txtDialogCancel:
                        Utils.dismissDialog();
                        break;
                    case R.id.txtDialogSure:
                        omPresenter.cancelOrder(context,orderID);
                        Utils.dismissDialog();
                        break;
                }
            }
        });
    }

    private static final int SDK_PAY_FLAG = 1;

    private static final int SDK_CHECK_FLAG = 2;

    String aliinfo="";

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);

                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();

                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        finish();
                        Utils.showToast(LookOrderActivity.this, "支付成功");
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Utils.showToast(LookOrderActivity.this,"支付结果确认中");
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Utils.showToast(LookOrderActivity.this, "支付失败");

                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    if (!(boolean) msg.obj)
                        Utils.showToast(LookOrderActivity.this, "检查结果为：" + msg.obj);
                    else {

                    }
                    break;
                }
                default:
                    break;
            }
        };
    };


    private void pay(){

        PayActivePresenter presenter = new PayActivePresenter(this, this, logId, oiModel.getOrder_amount(), oiModel.getPay_id());
        if (oiModel.getPay_id().equals("1"))
        {
            presenter.LoadAliPay();
        }else {
            presenter.LoadWXPay();
        }
//        Intent intent = new Intent(context,PayActivity.class);
//        intent.putExtra("class",1);
//        intent.putExtra("ordernumber",oiModel.getOrder_sn());
//        intent.putExtra("ordermoney",oiModel.getOrder_amount());
//        startActivity(intent);
    }
    //对订单操作的返回
    @Override
    public void result(BaseModel model) {
        if(model.getCode().equals("1"))
            oiPresenter.loadOrderInfor(context, orderID);
        Utils.showToast(context,model.getMsg());
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        OrderGoods model = (OrderGoods) adapterView.getItemAtPosition(i);
        Intent intent = new Intent(context, GoodsInfoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("goodsId", model.getGoods_id());
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    public void getWXinfo(WXpayModel wxpay) {
        if (wxpay.getCode().equals("1")) {
            final IWXAPI api = WXAPIFactory.createWXAPI(this, null);
            // 将该app注册到微信
            api.registerApp(ConfigValue.WXAPP_ID);

            PayReq req = new PayReq();

            req.appId = wxpay.getData().getPayinfo().getAppId();

            req.partnerId = wxpay.getData().getPayinfo().getPartnerId();
            req.prepayId = wxpay.getData().getPayinfo().getPrepayId();
            req.packageValue = "Sign=WXPay";
            req.nonceStr = wxpay.getData().getPayinfo().getNonceStr();
            req.timeStamp = wxpay.getData().getPayinfo().getTimeStamp();
            req.sign = wxpay.getData().getPayinfo().getSign();
            api.sendReq(req);


            finish();
        }else {
            Toast.makeText(this,wxpay.getMsg(),Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void getALiinfo(AliPatModel ali) {
        aliinfo=ali.getData().getPayinfo();
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    public void  Ali(String msg )
    {
        aliinfo=msg;
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    Runnable payRunnable = new Runnable() {

        @Override
        public void run() {
            PayTask alipay = new PayTask(LookOrderActivity.this);
            String result = alipay.pay(aliinfo);

            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        }
    };

    public class NumberSelectDialog extends Dialog {

        private Context context;
        private Button btn_sure;
        private Button btn_cencle;
        private EditText et_number;

        private int pnum;

        public NumberSelectDialog(Context context) {
            super(context, R.style.Theme_AppCompat_Dialog);
            // TODO Auto-generated constructor stub
            this.context = context;

            setdialog();
        }

        public void setdialog() {
            View view = LayoutInflater.from(context).inflate(
                    R.layout.numberselect_dialog, null);
            btn_cencle = (Button) view.findViewById(R.id.nsd_btn_cencle);

            et_number = (EditText) view.findViewById(R.id.nsd_et_num);

            super.setContentView(view);

        }

        public String getnum() {

            return et_number.getText().toString();


        }

        /**
         * 确定键监听器
         *
         * @param listener
         */

        public void setOnPositiveListener(View.OnClickListener listener) {
            btn_cencle.setOnClickListener(listener);
        }
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (windoe != null
                    && windoe.isShowing()) {
                windoe.dismiss();
                return true;
            }

        }
        return super.onKeyDown(keyCode, event);
    }


}
